<?php
// api/db.php

// CONFIGURATION FOR HOSTINGER
// Update these values with your Hostinger Database credentials
$host = 'localhost';
$dbname = 'u492750473_site'; // Example Hostinger DB name
$username = 'u492750473_site'; // Example Hostinger DB user
$password = 'm8CMVt3dnM?'; // UPDATE THIS WITH REAL PASSWORD

// Auto-detect environment (Local vs Production)
$is_local = ($_SERVER['SERVER_NAME'] === 'localhost' || $_SERVER['SERVER_NAME'] === '127.0.0.1');

try {
    if ($is_local) {
        // Use SQLite for local testing implies no setup needed
        // Creating the DB file in the parent folder to avoid being web-accessible if possible, or just same folder for simplicity
        $pdo = new PDO('sqlite:../database.sqlite');
    } else {
        // Use MySQL for Hostinger
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    }
    
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    // Auto-create table if not exists (Simple migration for single user usage)
    $tableSql = $is_local 
        ? "CREATE TABLE IF NOT EXISTS progress (id INTEGER PRIMARY KEY, data TEXT, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)"
        : "CREATE TABLE IF NOT EXISTS progress (id INT PRIMARY KEY, data LONGTEXT, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";
    
    $pdo->exec($tableSql);

} catch (PDOException $e) {
    // Determine user friendly error
    http_response_code(500);
    die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
}
?>


